package com.leetcode.algorithm.y22.m09.w2;

import java.util.ArrayList;
import java.util.List;

/**
 * 54. 螺旋矩阵
 * 
 * https://leetcode.cn/problems/spiral-matrix/
 * 
 * @author jie.deng
 *
 */
class Question0054Solution01 {

	public List<Integer> spiralOrder(int[][] matrix) {
		List<Integer> result = new ArrayList<>();
		int m = matrix.length;
		int n = matrix[0].length;

		int loop = 0;
		int left = loop;
		int right = n - 1 - loop;
		int top = loop;
		int bottom = m - 1 - loop;
		while (left <= right && top <= bottom) {
			// top
			for (int col = left; col <= right; col++) {
				result.add(matrix[top][col]);
			}
			// right
			for (int row = top + 1; row < bottom; row++) {
				result.add(matrix[row][right]);
			}
			// bottom
			if (top < bottom) {
				for (int col = right; col >= left; col--) {
					result.add(matrix[bottom][col]);
				}
			}
			// left
			if (left < right) {
				for (int row = bottom - 1; row > top; row--) {
					result.add(matrix[row][left]);
				}
			}

			loop++;
			left = loop;
			right = n - 1 - loop;
			top = loop;
			bottom = m - 1 - loop;
		}

		return result;
	}

}